package com.clg.protobuf.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

/**
 * 动态编译
 * 动态加载Class
 * Created by chenlong on 2017/6/1.
 */
@Component
public class ClassUtil {

	private final Logger logger = LoggerFactory.getLogger(ClassUtil.class);

	/**
	 * 动态编译
	 */
	private int dynamicCompiler(String fialePath) {
		JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
		int flag = javac.run(null, null, null,fialePath);
		logger.info(flag == 0 ? "编译成功" : "编译失败");
		return flag;
	}

	/**
	 * 动态加载类
	 * @param fileName
	 * @return
	 * @throws ClassNotFoundException
	 */
	public Class dynamicLoad(String fileName) throws ClassNotFoundException {
		// 编译文件所在路径
		String filePath = ConstantUtil.PROTOBUF_JAVA_PATH + fileName;
		int compilerResult = this.dynamicCompiler(filePath + ".java");
		if (compilerResult == 0) {
			MyClassLoader classLoader = new MyClassLoader(filePath + ".class");
			// 这里要把包路径传入进去
			Class<?> clazz = classLoader.loadClass(ConstantUtil.PROTOBUF_PACKAGE_NAME + "." + fileName);
			return clazz;
		}
		return null;
	}
}
